import json

import requests

from applications.extensions import db
from mod.fun import tconf
from plugins.users.models import User


class Bj35Api():
    _url = 'https://uapi.bj35.com'
    _uid = ''
    _secret = ''
    _access_token = ''
    _userinfo = ''
    def __init__(self):
        self._uid = tconf('users', 'bj35user_uid')
        self._secret = tconf('users', 'bj35user_secret')
        self.get_token()
        if not self._access_token:
            raise Exception('三十五中用户API初始化失败')

    def get_token(self):
        url = self._url + '/getAccessToken'+'?uid=' + self._uid + '&secret=' + self._secret
        r = requests.get(url)
        if r.status_code == 200:
            data = r.json()
            if data['code'] == 1:
                self._access_token = data['data']['access_token']
                return True
            else:
                return False
        else:
            return False

    def userinfo(self, uid):
        url = self._url + '/ldap/searchuser' + '?access_token=' + self._access_token + '&uid=' + uid
        r = requests.get(url)
        if r.status_code == 200:
            data = r.json()
            # print(data['entries'][0])
            if data['code'] == 0:
                if len(data['entries']) ==1:
                    self._userinfo = data['entries'][0]
                    return data['entries'][0]['attributes']
                else:
                    return False
            else:
                return False
        else:
            return False

    def auth(self, username, password):
        url = self._url + '/ldap/auth' + '?access_token=' + self._access_token
        data = {
            'username': username,
            'password': password
        }
        r = requests.post(url, data=json.dumps(data))
        if r.status_code == 200:
            data = r.json()
            if data['code'] == 0:
                return data
            else:
                return False
        else:
            return False

    def sync_user(self, password):
        if not self._userinfo:
            return False
        tt = tconf('users', 'bj35user_usermap')
        if not tt:
            return False
        t = json.loads(tt)
        data = self._userinfo['attributes']
        udata = {
            'username': data[t['username']],
            'password': password,
            'truename': data[t['truename']],
            'email': data[t['email']],
            'mobile': data[t['mobile']],
            'idcard': data[t['idcard']],
            'cardid': data[t['cardid']],
            'usertype': self._get_usertype(),
            'basedn': data['dn'],
            'py': data['initials'],
            'pinyin': data['description'][0]
        }
        # 读取本地数据库中是否有数据；
        # 如果有，则更新；如果没有，则添加
        uinfo = User.query.filter_by(username=data[t['username']]).first()
        if uinfo:
            # update
            uinfo.update(udata)
        else:
            # add
            user = User(**udata)
            User.set_password(password)
            db.session.add(user)
        db.session.commit()
        return True


    def _get_usertype(self):
        userdn = self._userinfo['dn']
        td = tconf('users', 'bj35user_usertype')
        ut = '0'
        if not td:
            return '0'
        t = json.loads(td)
        for k in t.keys():
            if userdn.find(t[k]) > -1:
                ut = t[k]
                break
        return ut